﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using jade.domain.FIPAAgentManagement;
using jade.domain;
using jade.core;

namespace MultiAgentLib
{
    public class SearchDF1 : Agent
    {

        public override void setup()
        {
            ServiceDescription sd = new ServiceDescription();
            sd.setType("buyer");
            sd.setName(getLocalName());
            register(sd);

            try
            {
                DFAgentDescription dfd = new DFAgentDescription();
                DFAgentDescription[] result = DFService.search(this, dfd);

                Console.WriteLine("Search returns: " + result.Length + " elements");
                if (result.Length > 0)
                    Console.WriteLine(" " + result[0].getName());


                sd = new ServiceDescription();
                sd.setType("buyer");
                dfd.addServices(sd);
                result = DFService.search(this, dfd);
                Console.WriteLine("Search for BUYER: " + result.Length + " elements");
                if (result.Length > 0)
                    Console.WriteLine(" " + result[0].getName());

                sd.setType("seller");
                result = DFService.search(this, dfd);
                if (result == null) Console.WriteLine("Search1 returns null");
                else
                {
                    Console.WriteLine("Search for SELLER: " + result.Length + " elements");
                    if (result.Length > 0)
                        Console.WriteLine(" " + result[0].getName());
                }
            }
            catch (FIPAException fe) { Console.WriteLine(fe.StackTrace); }
        }

        void  register(ServiceDescription sd)
        {
            DFAgentDescription dfd = new DFAgentDescription();
            dfd.setName(getAID());
            dfd.addServices(sd);

            try
            {
                DFService.register(this, dfd);
            }
            catch (FIPAException fe) { Console.WriteLine(fe.StackTrace); }
        }

        AID getService(String service)
        {
            DFAgentDescription dfd = new DFAgentDescription();
            ServiceDescription sd = new ServiceDescription();
            sd.setType(service);
            dfd.addServices(sd);
            try
            {
                DFAgentDescription[] result = DFService.search(this, dfd);
                if (result.Length > 0)
                    return result[0].getName();
            }
            catch (Exception fe) { Console.WriteLine(fe.StackTrace); }
            return null;
        }

    }
}
